﻿using System;
using System.IO;
using System.Threading.Tasks;
using AbpProjectTemplate.Application.Configuration.Dtos;
using AbpProjectTemplate.Components.Auditing;
using AbpProjectTemplate.Components.Authorization;
using Newtonsoft.Json;

namespace AbpProjectTemplate.Application.Configuration
{
    /// <summary>
    /// 自定义配置
    /// </summary>
    /// <remarks>原样获取保存数据</remarks>
    [AppAuditTag("自定义配置")]
    public class CustomerSettingsAppService : ApplicationService
    {
        /// <summary>
        /// 获取自定义配置
        /// </summary>
        public async Task<dynamic> Get(string name)
        {
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), AppConsts.CustomerConfigFolder, $"{name}.json");
            if (!File.Exists(filePath))
                return new { };
            var content = await File.ReadAllTextAsync(filePath);
            return JsonConvert.DeserializeObject<dynamic>(content);
        }
        /// <summary>
        /// 修改自定义配置
        /// </summary>
        [AppAudited("修改")]
        [ManagerAuthorize(AppPermissions.System.SystemConfig)]
        public async Task Update(CustomerConfigSetInput input)
        {
            var folderPath = Path.Combine(Directory.GetCurrentDirectory(), AppConsts.CustomerConfigFolder);
            if (!Directory.Exists(folderPath))
                Directory.CreateDirectory(folderPath);
            var filePath = Path.Combine(folderPath, $"{input.Name}.json");
            var json = string.Empty;
            try
            {
                json = JsonConvert.SerializeObject(input.Value);
            }
            catch (Exception ex)
            {
                throw new AppUserFriendlyException($"配置值转换成json失败：{ex.Message}");
            }
            await File.WriteAllTextAsync(filePath, json);
        }
    }
}

